#!/usr/bin/env python3
"""
WeCollege 云函数调用替换脚本
自动将所有云函数调用替换为服务器API调用
"""

import os
import re
import shutil
from pathlib import Path

# 需要替换的文件列表
FILES_TO_REPLACE = [
    # 新闻模块
    'projects/campus/pages/news/detail/news_detail.js',
    
    # 用户模块
    'projects/campus/pages/my/reg/my_reg.js',
    'projects/campus/pages/my/index/my_index.js',
    'projects/campus/pages/my/edit/my_edit.js',
    
    # 表白墙模块
    'projects/campus/pages/board/add/board_add.js',
    'projects/campus/pages/board/edit/board_edit.js',
    'projects/campus/pages/board/detail/board_detail.js',
    
    # 兼职模块
    'projects/campus/pages/job/add/job_add.js',
    'projects/campus/pages/job/edit/job_edit.js',
    'projects/campus/pages/job/detail/job_detail.js',
    
    # 失物招领模块
    'projects/campus/pages/lost/add/lost_add.js',
    'projects/campus/pages/lost/edit/lost_edit.js',
    'projects/campus/pages/lost/detail/lost_detail.js',
    
    # 请假模块
    'projects/campus/pages/leave/add/leave_add.js',
    'projects/campus/pages/leave/edit/leave_edit.js',
    'projects/campus/pages/leave/detail/leave_detail.js',
    
    # 评论模块
    'projects/campus/pages/comment/add/comment_add.js',
    'projects/campus/pages/comment/list/comment_list.js',
    'projects/campus/pages/comment/my_list/comment_my_list.js',
    
    # 管理员模块
    'projects/campus/pages/admin/user/list/admin_user_list.js',
    'projects/campus/pages/admin/user/detail/admin_user_detail.js',
    'projects/campus/pages/admin/user/export/admin_user_export.js',
    'projects/campus/pages/admin/mgr/add/admin_mgr_add.js',
    'projects/campus/pages/admin/mgr/edit/admin_mgr_edit.js',
    'projects/campus/pages/admin/mgr/list/admin_mgr_list.js',
    'projects/campus/pages/admin/mgr/pwd/admin_mgr_pwd.js',
    'projects/campus/pages/admin/mgr/log/admin_log_list.js',
    'projects/campus/pages/admin/news/list/admin_news_list.js',
    'projects/campus/pages/admin/news/edit/admin_news_edit.js',
    'projects/campus/pages/admin/news/add/admin_news_add.js',
    'projects/campus/pages/admin/board/list/admin_board_list.js',
    'projects/campus/pages/admin/board/export/admin_board_export.js',
    'projects/campus/pages/admin/job/list/admin_job_list.js',
    'projects/campus/pages/admin/job/export/admin_job_export.js',
    'projects/campus/pages/admin/lost/list/admin_lost_list.js',
    'projects/campus/pages/admin/lost/export/admin_lost_export.js',
    'projects/campus/pages/admin/leave/list/admin_leave_list.js',
    'projects/campus/pages/admin/leave/export/admin_leave_export.js',
    'projects/campus/pages/admin/index/home/admin_home.js',
    'projects/campus/pages/admin/setup/qr/admin_setup_qr.js',
    'projects/campus/pages/admin/setup/about/admin_setup_about.js',
    'projects/campus/pages/admin/preview/admin_preview.js',
    
    # 其他模块
    'projects/campus/pages/default/index/default_index.js',
    'projects/campus/biz/project_index_bh.js',
    'comm/biz/admin_biz.js',
    'comm/biz/fav_biz.js',
    'comm/behavior/my_fav_bh.js',
    'comm/behavior/about_bh.js',
    'cmpts/public/form/form_show/form_show_cmpt.js'
]

# 云函数路由到服务器API路由的映射
ROUTE_MAPPING = {
    # 用户相关
    'passport/login': 'user/login',
    'passport/register': 'user/register',
    'passport/my_detail': 'user/profile',
    'passport/edit_base': 'user/updateProfile',
    'passport/phone': 'user/getPhone',
    
    # 帖子相关 (表白墙、兼职、失物、请假都映射到帖子API)
    'board/insert': 'post/insert',
    'board/edit': 'post/update',
    'board/detail': 'post/getSingle',
    'board/view': 'post/visit',
    'board/like': 'post/like',
    'board/list': 'post/query',
    'board/del': 'post/delete',
    'board/status': 'post/status',
    
    'job/insert': 'post/insert',
    'job/edit': 'post/update',
    'job/detail': 'post/getSingle',
    'job/view': 'post/visit',
    'job/like': 'post/like',
    'job/list': 'post/query',
    'job/del': 'post/delete',
    'job/status': 'post/status',
    
    'lost/insert': 'post/insert',
    'lost/edit': 'post/update',
    'lost/detail': 'post/getSingle',
    'lost/view': 'post/visit',
    'lost/like': 'post/like',
    'lost/list': 'post/query',
    'lost/del': 'post/delete',
    'lost/status': 'post/status',
    
    'leave/insert': 'post/insert',
    'leave/edit': 'post/update',
    'leave/detail': 'post/getSingle',
    'leave/view': 'post/visit',
    'leave/like': 'post/like',
    'leave/list': 'post/query',
    'leave/del': 'post/delete',
    'leave/status': 'post/status',
    
    # 评论相关
    'comment/insert': 'comment/insert',
    'comment/del': 'comment/delete',
    'comment/like': 'comment/like',
    'comment/list': 'comment/queryByPost',
    
    # 新闻相关
    'news/detail': 'news/getSingle',
    'news/view': 'news/visit',
    'news/list': 'news/query',
    
    # 管理员相关
    'admin/login': 'admin/login',
    'admin/user_list': 'admin/user/list',
    'admin/user_del': 'admin/user/delete',
    'admin/user_status': 'admin/user/status',
    'admin/user_detail': 'admin/user/detail',
    'admin/user_data_get': 'admin/user/export/data',
    'admin/user_data_export': 'admin/user/export/excel',
    'admin/user_data_del': 'admin/user/export/clear',
    
    'admin/mgr_insert': 'admin/manager/insert',
    'admin/mgr_edit': 'admin/manager/update',
    'admin/mgr_del': 'admin/manager/delete',
    'admin/mgr_status': 'admin/manager/status',
    'admin/mgr_detail': 'admin/manager/detail',
    'admin/mgr_pwd': 'admin/manager/password',
    'admin/log_clear': 'admin/log/clear',
    
    'admin/news_insert': 'admin/news/insert',
    'admin/news_edit': 'admin/news/update',
    'admin/news_del': 'admin/news/delete',
    'admin/news_status': 'admin/news/status',
    'admin/news_detail': 'admin/news/detail',
    'admin/news_sort': 'admin/news/sort',
    'admin/news_vouch': 'admin/news/vouch',
    
    'admin/board_del': 'admin/post/delete',
    'admin/board_status': 'admin/post/status',
    'admin/board_sort': 'admin/post/sort',
    'admin/board_data_get': 'admin/post/export/data',
    'admin/board_data_export': 'admin/post/export/excel',
    'admin/board_data_del': 'admin/post/export/clear',
    
    'admin/job_del': 'admin/post/delete',
    'admin/job_status': 'admin/post/status',
    'admin/job_sort': 'admin/post/sort',
    'admin/job_data_get': 'admin/post/export/data',
    'admin/job_data_export': 'admin/post/export/excel',
    'admin/job_data_del': 'admin/post/export/clear',
    
    'admin/lost_del': 'admin/post/delete',
    'admin/lost_status': 'admin/post/status',
    'admin/lost_sort': 'admin/post/sort',
    'admin/lost_data_get': 'admin/post/export/data',
    'admin/lost_data_export': 'admin/post/export/excel',
    'admin/lost_data_del': 'admin/post/export/clear',
    
    'admin/leave_del': 'admin/post/delete',
    'admin/leave_status': 'admin/post/status',
    'admin/leave_sort': 'admin/post/sort',
    'admin/leave_data_get': 'admin/post/export/data',
    'admin/leave_data_export': 'admin/post/export/excel',
    'admin/leave_data_del': 'admin/post/export/clear',
    
    'admin/home': 'admin/dashboard',
    'admin/clear_vouch': 'admin/clearVouch',
    'admin/setup_qr': 'admin/setup/qr',
    
    # 收藏相关
    'fav/update': 'favorite/toggle',
    'fav/is_fav': 'favorite/check',
    'fav/del': 'favorite/delete',
    
    # 首页相关
    'home/list': 'home/data',
    'home/setup_get': 'common/setup',
    
    # 内容检查
    'check/img': 'common/imageCheck'
}

def backup_file(file_path):
    """备份文件"""
    backup_path = file_path + '.backup'
    if os.path.exists(file_path) and not os.path.exists(backup_path):
        shutil.copy2(file_path, backup_path)
        print(f"已备份: {file_path} -> {backup_path}")

def replace_cloud_calls(content):
    """替换云函数调用"""
    
    # 1. 替换 cloudHelper 引用
    content = re.sub(
        r"const cloudHelper = require\(['\"].*?cloud_helper\.js['\"]",
        "const serverHelper = require('../../helper/server_helper.js')",
        content
    )
    
    # 2. 替换方法调用
    replacements = [
        ('cloudHelper.callCloudSumbit', 'serverHelper.callServerSumbit'),
        ('cloudHelper.callCloudData', 'serverHelper.callServerData'),
        ('cloudHelper.callCloudSumbitAsync', 'serverHelper.callServerSumbitAsync'),
        ('cloudHelper.callCloud', 'serverHelper.callServer'),
        ('cloudHelper.dataList', 'serverHelper.dataList'),
        ('cloudHelper.transTempPics', 'serverHelper.uploadImages'),
        ('cloudHelper.transTempPicOne', 'serverHelper.uploadImageOne'),
    ]
    
    for old, new in replacements:
        content = content.replace(old, new)
    
    # 3. 替换路由
    for old_route, new_route in ROUTE_MAPPING.items():
        # 匹配引号内的路由
        pattern = f"['\"]({re.escape(old_route)})['\"]"
        replacement = f"'{new_route}'"
        content = re.sub(pattern, replacement, content)
    
    return content

def process_file(file_path):
    """处理单个文件"""
    full_path = os.path.join('miniprogram', file_path)
    
    if not os.path.exists(full_path):
        print(f"文件不存在: {full_path}")
        return
    
    # 备份文件
    backup_file(full_path)
    
    # 读取文件内容
    try:
        with open(full_path, 'r', encoding='utf-8') as f:
            content = f.read()
    except Exception as e:
        print(f"读取文件失败 {full_path}: {e}")
        return
    
    # 替换内容
    new_content = replace_cloud_calls(content)
    
    # 如果内容有变化，写入文件
    if new_content != content:
        try:
            with open(full_path, 'w', encoding='utf-8') as f:
                f.write(new_content)
            print(f"已更新: {full_path}")
        except Exception as e:
            print(f"写入文件失败 {full_path}: {e}")
    else:
        print(f"无需更新: {full_path}")

def replace_core_files():
    """替换核心文件"""
    core_replacements = [
        ('miniprogram/app.js', 'miniprogram/app_new.js'),
        ('miniprogram/helper/cloud_helper.js', 'miniprogram/helper/server_helper.js'),
        ('miniprogram/comm/biz/passport_biz.js', 'miniprogram/comm/biz/passport_biz_new.js'),
        ('miniprogram/helper/content_check_helper.js', 'miniprogram/helper/content_check_helper_new.js'),
    ]
    
    for old_file, new_file in core_replacements:
        if os.path.exists(old_file):
            backup_file(old_file)
            if os.path.exists(new_file):
                shutil.copy2(new_file, old_file)
                print(f"已替换核心文件: {old_file}")
            else:
                print(f"新文件不存在: {new_file}")
        else:
            print(f"原文件不存在: {old_file}")

def main():
    """主函数"""
    print("开始WeCollege云函数到服务器API迁移...")
    print("=" * 50)
    
    # 检查是否在正确的目录
    if not os.path.exists('miniprogram'):
        print("错误: 请在WeCollege项目根目录下运行此脚本")
        return
    
    # 1. 替换核心文件
    print("\n1. 替换核心文件...")
    replace_core_files()
    
    # 2. 处理业务文件
    print("\n2. 处理业务文件...")
    for file_path in FILES_TO_REPLACE:
        process_file(file_path)
    
    print("\n" + "=" * 50)
    print("迁移完成!")
    print("\n请注意:")
    print("1. 在 miniprogram/setting/api_config.js 中配置您的服务器地址")
    print("2. 测试所有功能确保正常工作")
    print("3. 原文件已备份为 .backup 后缀")
    print("4. 如有问题可以使用备份文件恢复")

if __name__ == '__main__':
    main()